import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import styles from './index.module.scss';
import { useFormik } from 'formik';
import { useDispatch } from 'react-redux';
import { loginAction, sendCodeAction } from '@/store/action/user';
import { Toast } from 'antd-mobile';
import { useEffect, useRef, useState } from 'react';
import { useHistory, useLocation } from 'react-router-dom';

type FormValues = {
  mobile: string;
  code: string;
};

export default function Login() {
  const [time, setTime] = useState(0);
  const dispatch = useDispatch();
  const timeRef = useRef(-1);
  const history = useHistory();
  const location = useLocation<{ from: string }>();
  // console.log(location);
  //组件卸载时清除定时器，防止内存泄漏
  useEffect(() => {
    return () => {
      clearInterval(timeRef.current);
    };
  }, []);
  const handleSendCode = async () => {
    if (formik.errors.mobile)
      Toast.show({ content: formik.errors.mobile, duration: 1000 });

    if (time > 0) return;
    //调用异步action,发起请求
    await dispatch(sendCodeAction(formik.values.mobile));
    Toast.show({ content: '获取验证码成功', duration: 1000 });
    //60秒才可以发一次验证码，当获取验证码成功后，启动定时器，60s后再能再次发起请求
    setTime(60);
    //直接使用定时器，组件卸载时无法清除，所以使用ref来临时保存timeid，组件卸载时清除
    timeRef.current = window.setInterval(() => {
      //需要使用箭头函数返回，否则内部获取不到time的最新值（setState异步）
      setTime((time) => {
        if (time === 1) {
          clearInterval(timeRef.current);
        }
        return time - 1;
      });
    }, 1000);
  };
  const formik = useFormik({
    initialValues: {
      mobile: '13580478281',
      code: '123456',
    },
    onSubmit: async (values) => {
      console.log(values);
      //调用异步action，发起登录请求
      await dispatch(loginAction(values));
      Toast.show({ content: '登录成功！', duration: 1000 });
      //判断是否有保存路径

      const target = location.state ? location.state.from : '/';
      history.push(target);
    },
    validate(values) {
      const errors = {} as FormValues;
      if (!/^1[3-9]\d{9}$/.test(values.mobile)) {
        errors.mobile = '手机号码格式错误';
      }
      if (!/^\d{6}$/.test(values.code)) {
        errors.code = '验证码格式错误';
      }
      return errors;
    },
  });
  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={formik.handleSubmit}>
          {/* 手机号输入框 */}
          <div className="input-item">
            <div className="input-box">
              <Input
                autoFocus
                className="input"
                placeholder="请输入手机号"
                autoComplete="off"
                type="text"
                name="mobile"
                maxLength={11}
                value={formik.values.mobile}
                onChange={formik.handleChange}
                errorMsg={formik.touched.mobile ? formik.errors.mobile : ''}
                onBlur={formik.handleBlur}
              />
            </div>
          </div>

          {/* 短信验证码输入框 */}
          <div className="input-item">
            <div className="input-box">
              <Input
                className="input"
                placeholder="请输入验证码"
                autoComplete="off"
                type="text"
                name="code"
                maxLength={6}
                extra={
                  <span onClick={() => handleSendCode()}>
                    {time === 0 ? '获取验证码' : `${time}s后重试`}
                  </span>
                }
                value={formik.values.code}
                onChange={formik.handleChange}
                errorMsg={formik.touched.code ? formik.errors.code : ''}
                onBlur={formik.handleBlur}
              />
              {/* <div className="extra" onClick={() => handleSendCode()}>
                获取验证码
              </div> */}
            </div>
          </div>

          {/* 登录按钮 */}
          <button
            type="submit"
            className="login-btn"
            disabled={!formik.isValid}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  );
}
